package lj.courseinterect.dao;

import lj.courseinterect.dao.i.ExamInfoDao;
import lj.courseinterect.dao.i.NoticeInfoDao;
import lj.courseinterect.entity.ExamInfo;
import lj.courseinterect.entity.NoticeInfo;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.List;

public class JpaNoticeInfoDao extends JpaDao<NoticeInfo, Long> implements NoticeInfoDao{

    public JpaNoticeInfoDao() {
        super(NoticeInfo.class);
    }


    
    @Override
    @Transactional(readOnly = true)
    public List<NoticeInfo> queryByCouId(Long couId) {
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<NoticeInfo> criteriaQuery = builder.createQuery(this.entityClass);

        Root<NoticeInfo> root = criteriaQuery.from(this.entityClass);
        Path<String> namePath = root.get("couId");
        criteriaQuery.where(builder.equal(namePath, couId));


        TypedQuery<NoticeInfo> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
        List<NoticeInfo> noticeInfos= typedQuery.getResultList();

        if (noticeInfos.isEmpty()) {
            return null;
        }
        return noticeInfos;
    }

    @Override
    @Transactional(readOnly = true)
    public NoticeInfo findByCouId(Long couId) {
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<NoticeInfo> criteriaQuery = builder.createQuery(this.entityClass);

        Root<NoticeInfo> root = criteriaQuery.from(this.entityClass);
        Path<String> namePath = root.get("couId");
        criteriaQuery.where(builder.equal(namePath, couId)).orderBy(builder.desc(root.get("notTime")));


        TypedQuery<NoticeInfo> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
        List<NoticeInfo> noticeInfos = typedQuery.getResultList();
        if(noticeInfos.isEmpty()){
            return null;
        }

        return noticeInfos.get(0);
    }
}
